<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
%>
<div class="row-fluid" style="height: inherit;margin:0px;border: 0px">
<form action="" class="form-horizontal" id="baseInfor" name="materialForm" method="post" target="_ifr">
      <input type="hidden" id="id" name="id" value="${qc.id }">
      <div class="row" style="margin:0;padding:0;">
           <div class="control-group span6" style="display: inline">
                <label class="control-label" for="qualityNo" > 质检单编号：</label>
                <div class="controls">
                    <div class="input-append span12" >
                        <input type="text" id="qualityNo" class="span10" name="qualityNo" placeholder="后台自动生成" value='${qc.qualityNo }' readonly="readonly"/>
                    </div>
                </div>
           </div>
            <%--质检时间--%>
           <div class="control-group span6" style="display: inline">
                <label class="control-label" for="strCreatetime" >质检时间：</label>
                <div class="controls">
                    <div class="required span12" style=" float: none !important;">
                        <input type="text" class="form-control date-picker" id="strCreatetime" name="strCreatetime" placeholder="质检时间" value='${qc.strCreatetime }'/>
                    </div>
                </div>
           </div>
        </div>                
           <div class="row" style="margin:0;padding:0;">
            <%--ASN单号--%>
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="goodsId" >ASN单号：</label>
                <div class="controls">
                    <div class="required span12" style="float: none !important;">
                        <input class="span10" type="text" id="goodsId" name="goodsId" placeholder="ASN单号">
                    </div>
                </div>
            </div>
            <%-- 质检人--%>
            <div class="control-group span6" style="display: inline">
                <label class="control-label" for="qualityUser" > 质检人：</label>
                <div class="controls">
                    <div class="required span12" style=" float:none !important;">
                        <input type="text" class="span10" id="qualityUser" name="qualityUser" placeholder="质检人">
                    </div>
                </div>
            </div>
        </div>
    <div class="row" style="margin:0;padding:0;">
        <%--ASN单号--%>
        <div class="control-group span6" style="display: inline">
            <label class="control-label" for="quality" >质检库位：</label>
            <div class="controls">
                <div class="required span12" style="float:none !important;">
                    <input class="span10" type="text" id="quality" name="quality" placeholder="质检库位">
                </div>
            </div>
        </div>
    </div>     
      <div style="margin-left:10px;">
            <span class="btn btn-info" id="formSave">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
            <span class="btn btn-info" id="formSubmit" onclick = "refer();">
		        <i class="ace-icon fa fa-check bigger-110"></i>&nbsp;提交
            </span>
        </div>        
</form>
  <div id="materialDiv" style="margin:10px;">
        <!-- 下拉框 -->
        <label class="inline" for="materialInfor">物料：</label>
        <input type="text" id = "materialInfor" name="materialInfor" style="width:350px;margin-right:10px;" />
        <button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
            <i class="icon-plus" style="margin-right:6px;"></i>添加
        </button>       
    </div>
    <!-- 表格div -->
    <div id="grid-div-c" style="width:100%;margin:0px;border:0px;">      
        <!-- 	表格工具栏 -->
        <div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
            <div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
        <!-- 入库单信息表格 -->
        <table id="grid-table-c"></table>
        <!-- 表格分页栏 -->
        <div id="grid-pager-c"></div>
    </div>
</div>
<iframe src="about:blank" name="_ifr" height="0" class="hidden"></iframe>
<script type="text/javascript" src="<%=path%>/static/js/techbloom/wms/instorage/qualitycertificate/quality_detail.js"></script>
<script type="text/javascript">
    var context_path = '<%=path%>';
    var oriData;      //表格数据
    var _grid_detail;        //表格对象
    var lastsel2;
    var preStatus=${INSTORE.preStatus==null?0:INSTORE.preStatus};
    var selectData = 0;   //存放物料选择框中的值
    var selectParam = "";  //存放之前的查询条件
     
	    $("#qualityUser").select2({
	    placeholder: "选择质检员",
	    minimumInputLength: 0, //至少输入n个字符，才去加载数据
	    allowClear: true, //是否允许用户清除文本信息
	    delay: 250,
	    formatNoMatches: "没有结果",
	    formatSearching: "搜索中...",
	    formatAjaxError: "加载出错啦！",
	    ajax: {
	        url: context_path + "/ASNmanage/getSelectUser",
	        type: "POST",
	        dataType: 'json',
	        delay: 250,
	        data: function (term, pageNo) { //在查询时向服务器端传输的数据
	            term = $.trim(term);
	            return {
	                queryString: term, //联动查询的字符
	                pageSize: 15, //一次性加载的数据条数
	                pageNo: pageNo, //页码
	                time: new Date()
	                //测试
	            }
	        },
	        results: function (data, pageNo) {
	            var res = data.result;
	            if (res.length > 0) { //如果没有查询到数据，将会返回空串
	                var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
	                return {
	                    results: res,
	                    more: more
	                };
	            } else {
	                return {
	                    results: {}
	                };
	            }
	        },
	        cache: true
	    }	
	});    
    $("#baseInfor input[type=radio][name=preStatus][value="+preStatus+"]").attr("checked",true).trigger("click");
    $(".date-picker").datetimepicker({format: 'YYYY-MM-DD HH:mm:ss',useMinutes:true,useSeconds:true});     
    $("#baseInfor").validate({
    ignore: "",
    rules: {
        "qualityUser": {
            required: true,
        },
        "goodsId": {
            required: true,
        },
        "createtime": {
            required: true,
        },
        
    },
    messages: {
        "qualityUser": {
            required: "请选择质检人",
        },
        "goodsId": {
            required: "请选择ASN",
        },
        "createtime": {
            required: "请填写质检时间!",
        },
       
    },
    errorClass: "help-inline",
    errorElement: "span",
    highlight:function(element, errorClass, validClass) {
        $(element).parents('.control-group').addClass('error');
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).parents('.control-group').removeClass('error');
    }
});          
    //单据保存按钮点击事件
    $("#formSave").click(function(){
        
        if($('#baseInfor').valid()){
            //通过验证：获取表单数据，保存表单信息
            var formdata = $('#baseInfor').serialize();
            saveFormInfo(formdata);
        }
    });
    $('#baseInfor .mySelect2').select2();

    //初始化下拉框:入库类型选择
    //当选择下框的时候，将选中的值赋值给隐藏的输入框中，方便form表单获取
    $('#baseInfor #instorageTypeSelect').change(function(){
        $('#baseInfor #goodsId').val($('#baseInfor #instorageTypeSelect').val());
    });
    //初始化下拉框:质检人选择
    $('#baseInfor #qualityUserSelect').change(function(){
        $('#baseInfor #qualityUser').val($('#baseInfor #qualityUserSelect').val());
    });

    //清空物料多选框中的值
    function removeChoice(){
        $("#s2id_materialInfor .select2-choices").children(".select2-search-choice").remove();
        $("#materialInfor").select2("val","");
        selectData = 0;

    }

    $('[data-rel=tooltip]').tooltip();


    $('#materialInfor').select2({
        placeholder : "请选择物料",//文本框的提示信息
        minimumInputLength : 0, //至少输入n个字符，才去加载数据
        allowClear : true, //是否允许用户清除文本信息
        multiple: true,
        closeOnSelect:false,
        ajax : {
            url : context_path + '/qualityCertificate/getmaterialList',
            dataType : 'json',
            delay : 250,
            data : function(term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                selectParam = term;
                return {
                    goodsId:$("#baseInfor #goodsId").val(),
                    queryString : term, //联动查询的字符
                    pageSize : 15, //一次性加载的数据条数
                    pageNo : pageNo, //页码
                    time : new Date()
                    //测试
                }
            },
            results : function(data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results : res,
                        more : more
                    };
                } else {
                    return {
                        results : {
                            "id" : "0",
                            "text" : "没有更多结果"
                        }
                    };
                }

            },
            cache : true
        }
    });

    $('#materialInfor').on("change",function(e){
        var datas=$("#materialInfor").select2("val");
        selectData = datas;
        var selectSize = datas.length;
        if(selectSize>1){
            var $tags = $("#s2id_materialInfor .select2-choices");   //
            //$("#s2id_materialInfor").html(selectSize+"个被选中");
            var $choicelist = $tags.find(".select2-search-choice");
            var $clonedChoice = $choicelist[0];
            $tags.children(".select2-search-choice").remove();
            $tags.prepend($clonedChoice);
            $tags.find(".select2-search-choice").find("div").html(selectSize+"个被选中");
            $tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
            $tags.find(".select2-search-choice").find("a").attr("href","#");
            $tags.find(".select2-search-choice").find("a").attr("onclick","removeChoice();");
        }
        //执行select的查询方法
        $("#materialInfor").select2("search",selectParam);
    });

    //表单验证
    $('#baseInfor').validate({
    });

    //工具栏
    $("#__toolbar__-c").iToolBar({
        id:"__tb__01",
        items:[
            {label:"删除", onclick:delDetail}
// 	   	 	{label:"查询", onclick:openDetailListSearchPage}
        ]
    });

    //单元格编辑成功后，回调的函数
    var editFunction = function eidtSuccess(XHR){
        /* var returnData = XHR.responseText;
        Dialog.alert(returnData); */
        var data = eval("("+XHR.responseText+")");
        if(data["msg"]!=""){
            layer.alert(data["msg"]);
        }
        jQuery("#grid-table-c").jqGrid('setGridParam',
            {
                postData: {
                    id:$('#id').val(),
                    queryJsonString:""
                }
            }
        ).trigger("reloadGrid");
    };

    //初始化表格
   _grid_detail= $("#grid-table-c").jqGrid({
        url : context_path + '/qualityCertificate/DetailList?qId='+$("#baseInfor #id").val(),
        datatype : "json",
        colNames : [ '物料主键','物料编号','物料名称','批次号','应收数量','实收数量','样本数量','合格数量','合格百分比(%)','计算合格率'],
        colModel : [
            {name : 'id',index : 'id',width : 55,hidden:true},
            {name : 'materialNo',index:'materialNo',width : 50},
            {name : 'materialName',index:'materialName',width : 50},
            {name : 'batchNo',index:'batchNo',width : 100},
            {name : 'amount',index:'amount',width : 50},
            {name : 'qualityAmount',index:'qualityAmount',width : 50/*,editable : true,editrules: {custom: true, custom_func: numberRegex}*/},
            {name : 'sampleAmount',index:'sampleAmount',width : 50,editable : true,editrules: {custom: true, custom_func: numberQualityAmount}},
            {name : 'eligibility',index:'eligibility',width : 50,editable : true,editrules: {custom: true, custom_func: numberSampleAmount}},
            {name : 'rate',index:'rate',width : 50},
            {name :'',index:'',width:50,formatter:function(cellValu, option, rowObject){
                    return '<div style="margsin-bottom:5px" class="btn btn-xs btn-success" onclick="calculate('+rowObject.id+','+rowObject.sampleAmount+','+rowObject.eligibility+')">确认</div>';
                }
            }
        ],
        rowNum : 20,
        rowList : [ 10, 20, 30 ],
        pager : '#grid-pager-c',
        sortname : 'ID',
        sortorder : "asc",
        altRows: true,
        viewrecords : true,
        autowidth:true,
        multiselect:true,
        multiboxonly: true,
        loadComplete : function(data){
            var table = this;
            setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
            oriData = data;
            $(window).triggerHandler('resize.jqGrid');
        },
        cellurl : context_path + "/qualityCertificate/saveamount",
        cellEdit: true,
        afterSaveCell:reloadDetailTableList,
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#grid-table-c").navGrid('#grid-pager-c',{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd('#grid-pager-c',{
            caption:"",
            buttonicon:"ace-icon fa fa-refresh green",
            onClickButton: function(){
                $("#grid-table-c").jqGrid('setGridParam',
                    {
                        url:context_path + '/qualityCertificate/DetailList',
                        postData: {qId:$("#baseInfor #id").val(),queryJsonString:""} //发送数据  :选中的节点
                    }
                ).trigger("reloadGrid");
            }
        });

    $(window).on("resize.jqGrid", function () {
        $("#grid-table-c").jqGrid("setGridWidth", $("#grid-div-c").width()-3);
        var height = $(".layui-layer-title",_grid_detail.parents(".layui-layer")).height()+
            $("#baseInfor").outerHeight(true)+$("#materialDiv").outerHeight(true)+
            $("#grid-pager-c").outerHeight(true)+$("#fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
          //$("#gview_grid-table-c .ui-jqgrid-titlebar").outerHeight(true)+
            $("#gview_grid-table-c .ui-jqgrid-hbox").outerHeight(true);
            $("#grid-table-c").jqGrid("setGridHeight",_grid_detail.parents(".layui-layer").height()-height);
    });
    $(window).triggerHandler("resize.jqGrid");
    if($("#id").val()!=""){
        reloadDetailTableList();   //重新加载详情列表
    }

    //将数据格式化成两位小数：四舍五入
    function formatterNumToFixed(value,options,rowObj){
        if(value!=null){
            var floatNum = parseFloat(value);
            return floatNum.toFixed(2);
        }else{
            return "0.00";
        }
    }

    //添加入库单详情
    function addDetail(){
        var id = $("#baseInfor #id").val();
        if(id=='-1'){
            layer.alert("请先保存表单信息！");
            return;
        }
        if(selectData!=0){
            //将选中的物料添加到数据库中
            $.ajax({
                type:"POST",
                url:context_path + '/qualityCertificate/saveDetail',
                data:{qualityId:$('#baseInfor #id').val(),materialId:selectData.toString()},
                dataType:"json",
                success:function(data){
                    removeChoice();   //清空下拉框中的值
                    if(data.result!=null){
                        if(data.msg){
                            layer.alert(data.msg+"已经存在,不能重复添加");
                        }else {
                            layer.alert("添加成功");
                        }
                        //重新加载详情表格
                        $("#grid-table-c").jqGrid('setGridParam',
                            {
                                postData: {qId:$("#baseInfor #id").val()} //发送数据  :选中的节点
                            }
                        ).trigger("reloadGrid");
                    }else{
                        layer.alert("添加失败");
                    }
                }
            });
        }else{
            layer.alert("请选择物料！");
        }
    }

    //搜索物料按钮：弹出物料搜索窗口
    function searchMaterial(){
        $.get( context_path +  "/qualityCertificate/toSearchDetailMaterialPage?qId="+$('#baseInfor #id').val()).done(function(data){
            childDiv = layer.open({
                title : "物料搜索",
                type:1,
                skin : "layui-layer-molv",
                area : ['900px', '500px'],
                shade : 0.6, //遮罩透明度
                moveType : 1, //拖拽风格，0是默认，1是传统拖动
                anim : 2,
                content : data
            });
        });
    }

    //物料详情数量编辑验证方法：只能为整数类型
    function mypricecheck(value, colname) {
        var reg = new RegExp("^[0-9]+(.[0-9]{1,4})?$");
        if(value!=""&&value!=0){
            if (!reg.test(value)) {
                return [ false, "非法单价！(注：可以有四位小数的正实数)" ];
            }else {
                return [ true, "" ];
            }
        }else{
            if($("#instorageTypeSelect").val()==3){
                return [ false, "请输入单价！" ];
            }else{
                return [ true, "" ];
            }
        }
    }
    //关闭当前窗口
    function closeWindowBtn(){
        layer.closeAll();
    }

    //数量输入验证
    function numberRegex(value, colname) {
    	
        var regex = /^\d+\.?\d{0,2}$/;
        if (!regex.test(value)) {
            return [false, "请输入整数"];
        }
        else  return [true, ""];
    }
    
    
    //数量输入验证
    function numberQualityAmount(value, colname) {
        var regex = /^\d+\.?\d{0,2}$/;
        selectID=$("#grid-table-c").getGridParam("selrow");  //只能获得选中一行的ID
        var strValue= $("#grid-table-c").jqGrid('getRowData',selectID).qualityAmount //这是获得 某一行的数据  ，后面可以加属性
        if (!regex.test(value)) {
            return [false, "请输入整数"];
        }
        if(parseInt(value)>parseInt(strValue)){
        	return [false];
        }
        else  return [true, ""];
    }
    
     //数量输入验证
    function numberSampleAmount(value, colname) {
        var regex = /^\d+\.?\d{0,2}$/;
        selectID=$("#grid-table-c").getGridParam("selrow");  //只能获得选中一行的ID
        var strValue= $("#grid-table-c").jqGrid('getRowData',selectID).sampleAmount //这是获得 某一行的数据  ，后面可以加属性
        if (!regex.test(value)) {
            return [false, "请输入整数"];
        }
        if(parseInt(value)>parseInt(strValue)){
        	return [false];
        }
        else  return [true, ""];
    }        
    //计算百分比
    function calculate(id,sampleAmount,eligibility){
        if(sampleAmount<=0){
            layer.alert("请输入样本数量");
        }
        if(eligibility<=0){
            layer.alert("请输入合格数量");
        }
        if(sampleAmount<eligibility){
        	layer.alert("合格数量不能超过样本数量");
        }else{
            //计算百分比以及更新状态
            $.ajax({
                type:"POST",
                dataType:"json",
                url:context_path + "/qualityCertificate/calculate",
                data:{id:id,sampleAmount:sampleAmount,eligibility:eligibility},
                success:function(data){
                    if(Boolean(data.result)){
                       reloadDetailTableList();
                       layer.msg("计算成功！",{icon:1,time:1200});
                    }else{
                       layer.msg(data.msg,{icon:2,time:2000});
                    }                   
                }
            })
        }
    }
    //提交
    function refer(){
        layer.confirm("确认提交,提交之后数据不能修改",function(){
            $.ajax({
                type:"POST",
                dataType:"json",
                url:context_path + "/qualityCertificate/queryOk",
                data:{id:$("#baseInfor #id").val()},
                success:function(data){
                    if(data.result){
                        layer.closeAll();
                        layer.msg("提交成功！",{icon:1,time:1200})
                        gridReload();
                    }else{
                        layer.msg(data.msg,{icon:1,time:2500});
                    }
                }
            })
        })

    }
    $("#goodsId").select2({
    placeholder: "选择ASN单据",
    minimumInputLength: 0, //至少输入n个字符，才去加载数据
    allowClear: true, //是否允许用户清除文本信息
    delay: 250,
    formatNoMatches: "没有结果",
    formatSearching: "搜索中...",
    formatAjaxError: "加载出错啦！",
    ajax: {
        url: context_path + "/qualityCertificate/getSelectASN",
        type: "POST",
        dataType: 'json',
        delay: 250,
        data: function (term, pageNo) { //在查询时向服务器端传输的数据
            term = $.trim(term);
            return {
                queryString: term, //联动查询的字符
                pageSize: 15, //一次性加载的数据条数
                pageNo: pageNo, //页码
                time: new Date()
                //测试
            }
        },
        results: function (data, pageNo) {
            var res = data.result;
            if (res.length > 0) { //如果没有查询到数据，将会返回空串
                var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                return {
                    results: res,
                    more: more
                };
            } else {
                return {
                    results: {}
                };
            }
        },
        cache: true
    }
  });
    $("#quality").select2({
        placeholder: "选择质检库位",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/qualityCertificate/getSelectQUA",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
  if($("#baseInfor #id").val()!="-1"){
    $.ajax({
           type:"POST",
           dataType:"json",
           url:context_path + "/qualityCertificate/getInfo",
           data:{id:$("#baseInfor #id").val()},
           success:function(data){
                 $("#qualityUser").select2('data',{
                  id:data.qc.qualityUser,
                  text:data.qc.userName
                 });
                 $("#goodsId").select2('data',{
                  id:data.qc.goodsId,
                  text:data.qc.goodsName
                 });
                   $("#quality").select2('data',{
                       id:data.qc.quality,
                       text:data.qc.locationName
                   });
            }
            });
  }
</script>
